import { _decorator, Component, Label, Node, Tween, tween, Vec3, UIOpacity } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Toast')
export class Toast extends Component {
    @property(Label)
    label: Label = null;

    @property(UIOpacity)
    uiOpacity: UIOpacity = null;

    private currentTween: Tween<Node> | null = null;

    show(message: string, duration: number = 2) {
        this.label.string = message;

        // 先停止上一个 tween
        if (this.currentTween) {
            this.currentTween.stop();
            this.currentTween = null;
        }

        // 重置透明度和缩放
        this.uiOpacity.opacity = 0;
        this.node.scale = new Vec3(0.8, 0.8, 1);
        this.node.active = true;

        // 新 tween 动画
        this.currentTween = tween(this.node)
            .call(() => {
                this.uiOpacity.opacity = 0;
            })
            .to(0.2, {
                scale: new Vec3(1, 1, 1),
            }, {
                easing: 'backOut',
                onUpdate: () => {
                    this.uiOpacity.opacity = Math.min(this.uiOpacity.opacity + 30, 255);
                }
            })
            .delay(duration)
            .to(0.3, {
                scale: new Vec3(0.8, 0.8, 1),
            }, {
                easing: 'fade',
                onUpdate: () => {
                    this.uiOpacity.opacity = Math.max(this.uiOpacity.opacity - 30, 0);
                }
            })
            .call(() => {
                this.node.active = false;
                this.currentTween = null;
            })
            .start();
    }
}
